<template>
  <div class="product-template-list-view">
    <!-- start 搜索 -->
    <div class="product-template-list-search-group">
      <!-- start  搜索header -->
      <form
        class="base-search"
        @submit.prevent="searchModel.pageNo=1;search();trackEventHandler('search')"
      >
        <div class="product-template-list-base-search-group">
          <el-input v-model="searchModel.key" placeholder="请输入主题、内容">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
          <base-button type="primary" native-type="submit">搜索</base-button>
          <base-button type="ghost" @event="resetParams">重置</base-button>
        </div>
        <span class="advanced-search-visible-btn" @click.self.stop="panelSearchAdvancedToggle">
          <i class="iconfont icon-add"></i>
          高级搜索
        </span>
      </form>
      <!-- end 搜索 header -->

      <!-- start 高级搜索表单 -->
      <product-template-search-panel
        :config="{fields: this.productFields}"
        ref="searchPanel"
      >
        <div class="advanced-search-btn-group" slot="footer">
          <base-button type="ghost" @event="resetParams">重置</base-button>
          <base-button type="primary" @event="powerfulSearch" native-type="submit">搜索</base-button>
        </div>
      </product-template-search-panel>
      <!-- end 高级搜索表单 -->
    </div>
    <!-- end 搜索 -->

    <!-- start content -->
    <div class="product-template-list-content">
     
      <!-- start 表格 -->
    <section style="padding:16px 16px 0;background:#fff;">
      <el-table
        :data="page.list"
        :row-key="getRowKey"
        stripe
        border
        :highlight-current-row="false"
        header-row-class-name="product-template-table-header"
        ref="productTemplateTable"
        class="product-template-table email-table bbx-normal-list-box"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!isLoading" :notice-msg="'暂无数据'"></BaseListForNoData>
        </template>
        <el-table-column
          v-for="column in columns"
          :key="column.field"
          :label="column.label"
          :prop="column.field"
          :width="column.width"
          :min-width="column.minWidth || '120px'"
          :sortable="column.sortable"
          show-overflow-tooltip
          :align="column.align"
        >
          <template slot-scope="scope">

            <!-- 发送人 -->
            <template v-if="column.field === 'sender'">
              {{ scope.row.senderName || '' }}
            </template>
           
            <!-- 收件人和抄送人 -->
            <template v-else-if="column.field === 'cc' || column.field === 'receiver'">
              <template v-if="scope.row[column.field] && scope.row[column.field].length">
                <template v-for="(user, index) in scope.row[column.field]">
                  <!-- 系统外成员 收件人和抄送人变成联系人了 -->
                  <span :key="index" class="mail-receiver">
                    {{ user.displayName || user.email || '' }}  
                    <el-tooltip v-if="!user.emailConfig" effect='dark' content='收件人未配置邮箱信息！' placement='top'>
                      <i class='iconfont icon-jinggao'></i>
                    </el-tooltip>
                  </span>
                  {{index+1 != scope.row[column.field].length ? '、' : ''}}
                </template> 
              </template>
            </template>

            <template v-else-if="column.field === 'status'">
              <span :class="scope.row.status == 1 ? 'success-text' : 'error-text'">{{ scope.row.status == 1 ? '成功' : '失败'}}</span>
            </template>
           
            <template v-else-if="column.field === 'sendTime'">{{ scope.row.sendTime | fmt_datetime }}</template>
            
            <template v-else-if="column.field === 'operation'">
              <span class="view-detail" @click="showDetail(scope.row)">查看</span>
            </template>

            <template v-else>{{scope.row[column.field]}}</template>
          </template>
        </el-table-column>
      </el-table>
    </section>
      <!-- end 表格 -->

      <!-- start 表格底部 -->
      <div class="table-footer">
        <div class="list-info">
          共
          <span class="level-padding">{{ page.total || 0 }}</span>记录
        </div>
        <el-pagination
          class="product-template-table-pagination"
          background
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="page.pageSize"
          :current-page="page.pageNo"
          layout="prev, pager, next, sizes, jumper"
          :total="page.total"
        ></el-pagination>
      </div>
      <!-- end 表格底部 -->

    </div>
    <!-- end content -->

    <base-table-advanced-setting ref="advanced"/>

    <!-- 邮件内容详情 -->
    <email-message-detail ref="emailDetailRef"></email-message-detail>

  </div>

</template>

<script>
import { fields, advancedFields } from '../EmailField';
import { isOpenData } from '@src/util/platform'
import Page from '@model/Page';
import SearchPanel from './SearchPanel.vue';
import EmailMessageDetail from './EmailMessageDetail.vue';
import { getRecords } from '@src/api/EmailApi';
import { defaultTableData } from '@src/util/table'

/* 高级搜索面板 列数 */
const MESSAGE_EMAIL_LIST_ADVANCE_SEARCH_COLUMN_NUMBER = 'message_email_search_column_number';
// 列表数据
const MESSAGE_EMAIL_LIST_DATA = 'message_email_list_data';

export default {
  name: 'email-message',
  props: {
    initData: {
      type: Object,
      default: () => ({})
    },
    isLoading:{
      type:Boolean,
      default:false
    }
  },
  data() {
    return {
      defaultTableData,
      isOpenData,
      emailDetail: {},
      emailContent: '',
      detailVisible: false,
      columns: fields, // 列
      columnNum: 1, // 高级搜索 列数
      page: new Page(), // page 对象
      productTemplateConfig: {
        productTemplateConfig: {},
        productFields: []
      }, // 产品配置项
      searchModel: {
        key: '',
        pageSize: 10,
        pageNo: 1,
        orderDetail: {},
        moreConditions: {}
      },
      productFields: advancedFields
    };
  },
  mounted() {
    this.search();
    window.__exports__refresh = this.search;
  },
  methods: {
    showDetail(item){
      this.$refs.emailDetailRef.open(item)
    },
    buildParams() {
      const sm = Object.assign({}, this.searchModel);
      let params = {
        key: sm.key,
        pageSize: sm.pageSize,
        pageNo: sm.pageNo
      };

      if (Object.keys(sm.orderDetail || {}).length) {
        params.orderDetail = sm.orderDetail;
      }

      if (Object.keys(sm.moreConditions).length > 0) {
        params = {
          ...params,
          ...sm.moreConditions
        };
      }

      return params;
    },
  
    // 页码数切换
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNo = 1;

      this.search();
    },
    // 跳转
    jump(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.search();
    },
    /* 获取本地数据 */
    localStorageGet(key) {
      try {
        const dataStr = localStorage.getItem(key) || '{}';
        return JSON.parse(dataStr);
      } catch (error) {
        console.log('error: ', error);
        return {};
      }
    },
    /* 设置本地数据 */
    localStorageSet(key, value, rootKey = null) {
      try {
        if (!rootKey) {
          localStorage.setItem(key, JSON.stringify(value));
        } else {
          const data = this.localStorageGet(rootKey);

          data[key] = value;
          localStorage.setItem(rootKey, JSON.stringify(data));
        }
      } catch (err) {
        console.log('localStorageSet err', err);
      }
    },
    // 搜索
    search() {
      const params = this.buildParams();
      this.$emit('pageLoading', true);
      return getRecords(params)
        .then(res => {
          this.$refs.searchPanel.close()
          this.$emit('pageLoading', false);
          this.page = res.data;
        })
        .catch(err => {
          this.$emit('pageLoading', false);
        });
    },
    // 搜索参数恢复
    paramsSearchRevert() {
      const localStorageData = this.localStorageGet(MESSAGE_EMAIL_LIST_DATA);

      if (localStorageData && localStorageData.pageSize) {
        this.searchModel.pageSize = Number(localStorageData.pageSize);
      }

      const num = localStorage.getItem(
        MESSAGE_EMAIL_LIST_ADVANCE_SEARCH_COLUMN_NUMBER
      ) || 1;
      this.columnNum = Number(num);
    },
    panelSearchAdvancedToggle() {
      window.TDAPP.onEvent('pc：邮件消息设置-高级搜索事件');
      this.$refs.searchPanel.open();

      this.$nextTick(() => {
        let forms = document.getElementsByClassName('advanced-search-form');
        for (let i = 0; i < forms.length; i++) {
          let form = forms[i];
          form.setAttribute('novalidate', true);
        }
      });
    },
    /**
     * @description 全量搜索
     */
    powerfulSearch() {
      this.searchModel.pageNo = 1;
      this.searchModel.moreConditions = this.$refs.searchPanel.buildParams();

      this.trackEventHandler('search');
      this.search();
    },
    resetParams() {
      window.TDAPP.onEvent('pc：邮件消息设置-重置事件');
      this.searchIncludeMoreConditions = false;
      this.searchModel = {
        key: '',
        pageNo: 1,
        pageSize: 10,
        orderDetail: {},
        moreConditions: {
          conditions: []
        }
      };

      this.$refs.searchPanel.resetParams();
      this.search();
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent('pc：邮件消息设置-搜索事件');
        return;
      }
    },
    getRowKey(row) {
      return row.id;
    },
  },
  components: {
    [SearchPanel.name]: SearchPanel,
    [EmailMessageDetail.name]: EmailMessageDetail,
  }
};
</script>

<style lang="scss" scoped>
.product-template-list-content .email-table {
  padding: 0;
}
.error-text {
  background: #FF4D4F;
}
.success-text {
  background: #00C853;
}
.loading-text {
  background: #FFA726;
}
.error-text,.success-text,.loading-text{
  padding:0px 6px;
  line-height:22px;
  border-radius: 11px;
  color:#fff;
  font-size: 12px;
}
.view-detail{
  color: $color-primary;
}
.mail-receiver {
  display: flex;
  i {
    color: #faae14;
    margin-left: 4px;
    margin-right: 2px;
  }
}
</style>